# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2023/4/24 8:41
# @Author : xyjiang1216
# @Email : jiangxuyan@nudt.edu.cn
# @File : construct_topo_from_file.py
# @Version: OpenPlanner2.0
import json

import networkx as nx


def read_graph(topo_filepath):
    """
    从topo_filepath中读取所有链路，
    并生成DiGraph类型的图
    :return G: 返回DiGraph
    """

    # 1. 读出link_set
    with open(topo_filepath, 'r') as f:
        link_set = json.load(f)
    # print(link_set)
    # 2. 将所有节点添加到图中
    G = nx.DiGraph()
    # 找到所有节点
    node_set = []
    for link in link_set:
        if link['src_node'] not in node_set:
            node_set.append(link['src_node'])
        if link['dst_node'] not in node_set:
            node_set.append(link['dst_node'])
    node_set.sort()
    # 添加节点
    for node in node_set:
        G.add_node(node)
    # 3. 将节点之间的边添加到图中
    for link in link_set:
        G.add_edge(link['src_node'], link['dst_node'], link_id=link['link_id'])

    # 4. 显示拓扑
    show_topology_graph(G)

    return G


import networkx as nx
from matplotlib import pyplot as plt


def show_topology_graph(graph, show=False, timeout=3):
    pos = nx.spring_layout(graph, iterations=200)  # 用 FR算法排列节点
    nx.draw(graph, pos, with_labels=True)
    labels = nx.get_edge_attributes(graph, 'link_id')
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=labels)
    # 显示3秒后关闭
    if show:
        plt.show(block=True)
        plt.pause(timeout)
        # plt.close('all')